package com.wsd.jing.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * All rights Reserved, Designed By www.tom.com
 *
 * @author tom
 * @version 1.0.0
 * @projectName: jing
 * @packageName: com.wsd.jing.utils
 * @className: RedisUtil
 * @description Redis工具类
 * @createDate 2024/7/10 20:30
 * @copyright 2024/7/10 20:30 www.tom.com Inc. All rights reserved.
 */
@Slf4j
@Component
public class RedisUtil {

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * @param key:   键
     * @param value: 值
     * @return boolean
     * @author tom
     * @description 设置缓存
     * @createDate 2024/7/10 20:38
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param key:     键
     * @param value:   值
     * @param timeout: 过期时间（秒）
     * @return boolean
     * @author tom
     * @description 设置缓存值且有过期时间
     * @createDate 2024/7/10 20:38
     */
    public boolean set(String key, Object value, long timeout) {
        try {
            if (timeout <= 0) {
                return set(key, value);
            }
            redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param key: 键
     * @return Object
     * @author tom
     * @description 获取缓存
     * @createDate 2024/7/10 20:37
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
}
